package com.cos.hospital.ui.patient.compare;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.cos.hospital.R;
import com.cos.hospital.code.Code;
import com.cos.hospital.init.BaseActivity;
import com.cos.hospital.model.UHttp;
import com.cos.hospital.model.bean.AcupointBean;
import com.cos.hospital.model.bean.ErrorBean;
import com.cos.hospital.model.bean.RecordWebBean;
import com.cos.hospital.model.bean.ResultBean;
import com.cos.hospital.model.bean.ResultListBean;
import com.cos.hospital.model.connector.HttpMsgListener;
import com.cos.hospital.tool.SPUtil;
import com.cos.hospital.tool.UDate;
import com.cos.hospital.tool.UPoPImages;
import com.cos.hospital.tool.UTxt;
import com.cos.hospital.tool.glide.UGlide;
import com.cos.hospital.ui.other.YinShiTuPianActivity;
import com.cos.hospital.ui.patient.compare.bean.ABBean;
import com.cos.hospital.ui.patient.compare.bean.RecordListBean;
import com.cos.hospital.ui.patient.compare.bean.SingleBean;
import com.cos.hospital.ui.patient.compare.bean.TimesBean;
import com.cos.hospital.ui.record.RecordCode;
import com.cos.hospital.widget.ProgressDialog;
import com.google.gson.JsonObject;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

/**
 * 患者档案
 */
public class CompareActivity extends BaseActivity implements CalendarView.OnCalendarSelectListener
        , CalendarView.OnCalendarInterceptListener, CalendarView.OnMonthChangeListener, CalendarView.OnYearChangeListener {
    @BindView(R.id.cmp_cal_root)
    View calendarRoot;
    @BindView(R.id.cmp_bg)
    ImageView iBg;
    @BindView(R.id.cmp_calendar)
    CalendarView calendarView;
    @BindView(R.id.cmp_mon_pick)
    TextView tMonthPick;

    @BindView(R.id.cmp_avatar)
    ImageView infoAvator;
    @BindView(R.id.cmp_name)
    TextView infoName;
    @BindView(R.id.cmp_sex)
    TextView infoSex;
    @BindView(R.id.cmp_old)
    TextView infoOld;

    @BindView(R.id.cmp_time_a)
    TextView aTime;
    @BindView(R.id.cmp_time_b)
    TextView bTime;
    @BindView(R.id.cmp_rc)
    RecyclerView rc;
    private ABAdapter abAdapter;
    private List<ABBean> abList;//已添加的元素

    private int patientId;//患者ID
    private int doctorId;//医生ID
    private int year, month, day;
    private boolean isForA;//A在选择时间
    private List<Date> dateList;
    private UPoPImages pImages;
    private static final long aDay = 1000L * 60 * 60 * 24;//1天

    @Override
    protected int layout() {
        return R.layout.activity_compare;
    }

    @Override
    protected void init() {
        setTitleLeftIcon();
        setTitleCenterTxt("对比病历");

        Intent intent = getIntent();
        patientId = intent.getIntExtra(Code.SP.ID, 0);
        doctorId = SPUtil.getUserId();

        infoName.setText(UTxt.isNull(intent.getStringExtra("user_name"), "????"));
        int fldSex = intent.getIntExtra("user_sex", 0);
        if (fldSex == 0) {
            infoSex.setText("女");
            Drawable drawable = ContextCompat.getDrawable(context, R.mipmap.ic_female);
            infoSex.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null);
        } else {
            infoSex.setText("男");
            Drawable drawable = ContextCompat.getDrawable(context, R.mipmap.ic_male);
            infoSex.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null);
        }
        int fldAge = intent.getIntExtra("user_age", 0);
        infoOld.setText(getString(R.string.unit_age, fldAge));
        String avator = intent.getStringExtra("user_avator");

        //初始化日期边界
        year = calendarView.getCurYear();
        month = calendarView.getCurMonth();
        day = calendarView.getCurDay();
        calendarView.setRange(2000, 1, 1, year, month, day);
        tMonthPick.setText(year + "年" + month + "月");
        calendarRoot.setVisibility(View.GONE);

        dateList = new ArrayList<>();
        abList = new ArrayList<>();
        abAdapter = new ABAdapter(abList, this);
        abAdapter.openLoadAnimation();//开启默认动画AlphaInAnimation
        rc.setLayoutManager(new LinearLayoutManager(context));
        abAdapter.setEmptyView(R.layout.lay_empty, rc);//设置当list中元素个数为0时显示的布局
//        rc.addItemDecoration(new MyDividerDecoration(
//            ContextCompat.getColor(context, R.color.white_bg), JUtils.dip2px(10)));
        rc.setAdapter(abAdapter);
    }

    @Override
    protected void logic() {
        UGlide.loadImage(this, R.mipmap.bg_info_full, iBg);
        //设置日期拦截事件，仅适用单选模式，当前无效
        calendarView.setOnCalendarInterceptListener(this);
        //日期选择事件
        calendarView.setOnCalendarSelectListener(this);
        //月份改变事件
        calendarView.setOnMonthChangeListener(this);
        //年份改变事件
        calendarView.setOnYearChangeListener(this);

        abAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (position < 0 || position > dateList.size()) {
                return;
            }
            ABBean bean = abList.get(position);
            if (bean == null) {
                showNotice("数据异常");
                return;
            }
            switch (view.getId()) {
                case R.id.ab_image_a_1://点击图片:
                    // pImages = UPoPImages.with(this).show(bean.getaRod().getImageList().get(0));
                    YinShiTuPianActivity.showTu(context, bean.getaRod().getImageList(), 0);
                    break;
                case R.id.ab_image_a_2://点击图片:
                    YinShiTuPianActivity.showTu(context, bean.getaRod().getImageList(), 1);
//                    pImages = UPoPImages.with(this).show(bean.getaRod().getImageList().get(1));
                    break;
                case R.id.ab_image_a_3://点击图片
//                    pImages = UPoPImages.with(this).show(bean.getaRod().getImageList().get(2));
                    YinShiTuPianActivity.showTu(context, bean.getaRod().getImageList(), 2);

                    break;
                case R.id.ab_image_b_1://点击图片:
//                    pImages = UPoPImages.with(this).show(bean.getbRod().getImageList().get(0));
                    YinShiTuPianActivity.showTu(context, bean.getbRod().getImageList(), 0);

                    break;
                case R.id.ab_image_b_2://点击图片:
//                    pImages = UPoPImages.with(this).show(bean.getbRod().getImageList().get(1));
                    YinShiTuPianActivity.showTu(context, bean.getbRod().getImageList(), 1);

                    break;
                case R.id.ab_image_b_3://点击图片
//                    pImages = UPoPImages.with(this).show(bean.getbRod().getImageList().get(2));
                    YinShiTuPianActivity.showTu(context, bean.getbRod().getImageList(), 2);
                    break;
            }
        });
        getUsed();
    }

    @OnClick({R.id.title_back, R.id.cmp_mon_pick, R.id.cmp_time_a, R.id.cmp_time_b, R.id.cmp_cal_root})
    public void click(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.cmp_mon_pick://点击选择月份:
                // TODO: 删掉吧
//                initComplte = true;
//                calendarView.showYearSelectLayout(year);
                break;
            case R.id.cmp_cal_root://时间点击日历外面:
                isForA = false;
                calendarRoot.setVisibility(View.GONE);
                break;
            case R.id.cmp_time_a://时间A:
                isForA = true;
                calendarRoot.setVisibility(View.VISIBLE);
                break;
            case R.id.cmp_time_b://时间B:
                isForA = false;
                calendarRoot.setVisibility(View.VISIBLE);
                break;

        }
    }

    /**
     * 获取使用的日期
     */
    private void getUsed() {
        ProgressDialog.getInstance().startProgressDialog(this);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("fldPatientId", patientId);
        jsonObject.addProperty("fldDoctorId", doctorId);
        UHttp.start(getServes().queryMedicalSupplement(jsonObject), "获取使用的日期", new HttpMsgListener<ResultListBean<TimesBean>>() {
            @Override
            public void onSubscribe(Disposable disposable) {
                addEvent(disposable);
            }

            @Override
            public void onError(String describe) {
                showNotice(describe);
            }

            @Override
            public void onFinish() {
                ProgressDialog.getInstance().stopProgressDialog();
            }

            @Override
            public void onSuccess(ResultListBean<TimesBean> dto) {
                if (dto.isSuccess()) {
                    List<TimesBean> result = dto.getResult();
                    if (result != null) {
                        for (TimesBean timesBean : result) {
                            if (!UTxt.isEmpty(timesBean.getTime())) {
                                dateList.add(UDate.strToDate(timesBean.getTime()));
                            }
                        }
                    } else {
                        showNotice(Code.DefaultPrompt);
                    }
                } else {
                    ErrorBean errorBean = dto.getError();
                    if (errorBean != null) {
                        showNotice(UTxt.isNull(errorBean.getMessage(), Code.DefaultPrompt));
                    } else {
                        showNotice(Code.DefaultPrompt);
                    }
                }
            }
        });
    }

    /**
     * 通过日期获取病历id
     */
    private void search(String date) {
        ProgressDialog.getInstance().startProgressDialog(this);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("fldPatientId", patientId);
        jsonObject.addProperty("fldDoctorId", doctorId);
        jsonObject.addProperty("time", date);
        UHttp.start(getServes().queryMedicalWithDate(jsonObject), "通过日期获取病历id", new HttpMsgListener<ResultBean<RecordListBean>>() {
            @Override
            public void onSubscribe(Disposable disposable) {
                addEvent(disposable);
            }

            @Override
            public void onError(String describe) {
                showNotice(describe);
                ProgressDialog.getInstance().stopProgressDialog();
            }

            @Override
            public void onSuccess(ResultBean<RecordListBean> dto) {
                if (dto.isSuccess()) {
                    RecordListBean result = dto.getResult();
                    if (result != null && result.getFldMedicalHistoryId() != 0) {
                        getInfo(result.getFldMedicalHistoryId());
                    } else {
                        ProgressDialog.getInstance().stopProgressDialog();
                        showNotice(Code.DefaultPrompt);
                    }
                } else {
                    ProgressDialog.getInstance().stopProgressDialog();
                    ErrorBean errorBean = dto.getError();
                    if (errorBean != null) {
                        showNotice(UTxt.isNull(errorBean.getMessage(), Code.DefaultPrompt));
                    } else {
                        showNotice(Code.DefaultPrompt);
                    }
                }
            }
        });
    }

    /**
     * 获取病历信息
     */
    private void getInfo(int fldMedicalHistoryId) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("id", fldMedicalHistoryId);
        UHttp.start(getServes().queryMedicalRecordInfo(jsonObject), "患者病历查询", new HttpMsgListener<ResultBean<RecordWebBean>>() {
            @Override
            public void onSubscribe(Disposable disposable) {
                addEvent(disposable);
            }

            @Override
            public void onError(String describe) {
                showNotice(describe);
            }

            @Override
            public void onFinish() {
                ProgressDialog.getInstance().stopProgressDialog();
            }

            @Override
            public void onSuccess(ResultBean<RecordWebBean> dto) {
                if (dto.isSuccess()) {
                    RecordWebBean recordBean = dto.getResult();
                    if (recordBean != null) {
                        List<RecordWebBean.MedicalElementBean> eleList = recordBean.getMedicalElement();
                        if (UTxt.isEmpty(eleList)) {
                            showNotice(Code.DefaultPrompt);
                            return;
                        }
                        List<RecordWebBean.MedicalImageBean> imageList = recordBean.getMedicalImage();
                        List<AcupointBean> acupoint = recordBean.getPatientTreatmentAcupoint();
                        RecordWebBean.MhfBean mhfBean = recordBean.getMhf();//月经公式
                        RecordWebBean.RhfBean rhfBean = recordBean.getRhf();//孕产公式

                        SingleBean singleBean;
                        String name;
                        //遍历元素
                        for (RecordWebBean.MedicalElementBean elementBean : eleList) {
                            name = elementBean.getFldElementName();
                            singleBean = new SingleBean();
                            int eleId = elementBean.getFldEleID();
                            singleBean.setFldEleID(eleId);
                            singleBean.setMainText(elementBean.getFldElementValue());
                            //经产史
                            if (elementBean.getFldEleID() == RecordCode.Type.MenstruationHistory) {
                                singleBean.setMhfBean(mhfBean);
                                singleBean.setRhfBean(rhfBean);
                            }
                            //有图片
                            if (!UTxt.isEmpty(imageList)) {
                                List<String> images = new ArrayList<>();
                                for (RecordWebBean.MedicalImageBean imageBean : imageList) {
                                    if (imageBean.getFldParentElementId() == elementBean.getId()) {
                                        images.add(imageBean.getFldImgPath());
                                    }
                                }
                                singleBean.setImageList(images);
                            }
                            //有学位
                            if (eleId == RecordCode.Type.AcupunctureRecord
                                    && !UTxt.isEmpty(acupoint)) {
                                singleBean.setAcuList(acupoint);
                                singleBean.setFldTreatmentDesc(recordBean.getFldTreatmentDesc()); // 其他治疗
                            }
                            addParaentList(singleBean, name, eleId, elementBean.getFldElementSort());
                        }
                        checkDatas(eleList);
                        abAdapter.notifyDataSetChanged();
                    } else {
                        ErrorBean errorBean = dto.getError();
                        if (errorBean != null) {
                            showNotice(UTxt.isNull(errorBean.getMessage(), Code.DefaultPrompt));
                        } else {
                            showNotice(Code.DefaultPrompt);
                        }
                    }
                }
            }
        });
    }

    /**
     * 检查元素，删除旧元素
     */
    private void checkDatas(List<RecordWebBean.MedicalElementBean> eleList) {
        ABBean bean;
        //置空元素
        for (int i = 0, leng = abList.size(); i < leng; i++) {
            bean = abList.get(i);
            boolean hasIt = false;
            for (int j = 0, lengJ = eleList.size(); j < lengJ; j++) {
                if (eleList.get(j).getFldEleID() == bean.getItemType()) {
                    hasIt = true;
                    break;
                }
            }
            if (!hasIt) {
                if (isForA) {
                    bean.setaRod(null);
                } else {
                    bean.setbRod(null);
                }
            }
            abList.set(i, bean);

        }
        //移除空元素
        Iterator<ABBean> iterator = abList.iterator();
        while (iterator.hasNext()) {
            bean = iterator.next();
            if (bean.getaRod() == null && bean.getbRod() == null) {
                iterator.remove();
            }
        }

        //排序
        Collections.sort(abList, (o1, o2) -> o1.getSorId() - o2.getSorId());
    }


    /**
     * 插入指定元素空间
     */
    private void addParaentList(SingleBean singleBean, String name, int eleId, int sorId) {
        int position = -1;
        for (int i = 0; i < abList.size(); i++) {
            if (abList.get(i).getItemType() == eleId) {
                position = i;
                break;
            }
        }
        if (isForA) {
            if (position == -1) {
                abList.add(new ABBean(eleId, singleBean, name, sorId));
            } else {
                ABBean bean = abList.get(position);
                bean.setaRod(singleBean);
                bean.setSorId(sorId);
                abList.set(position, bean);
            }
        } else {
            if (position == -1) {
                abList.add(new ABBean(singleBean, eleId, name, sorId));
            } else {
                ABBean bean = abList.get(position);
                bean.setbRod(singleBean);
                bean.setSorId(sorId);
                abList.set(position, bean);
            }
        }
    }

    @Override
    public void onCalendarOutOfRange(Calendar calendar) {

    }

    @Override
    public void onCalendarSelect(Calendar calendar, boolean isClick) {
        if (calendarRoot.isShown()) {
            year = calendar.getYear();
            month = calendar.getMonth();
            day = calendar.getDay();
            String date = year + "年" + month + "月" + day + "日";
            if (isForA) {
                if (date.equals(bTime.getText().toString())) {
                    showNotice("对比时间不能相同");
                    return;
                }
                aTime.setText(date);
            } else {
                if (date.equals(aTime.getText().toString())) {
                    showNotice("对比时间不能相同");
                    return;
                }
                bTime.setText(date);
            }
            search(date);
            calendarRoot.setVisibility(View.GONE);
        }
    }


    @Override
    public boolean onCalendarIntercept(Calendar calendar) {
        if (calendarRoot.isShown()) {
            for (Date date : dateList) {
//                if (Math.abs(date.getTime() - calendar.getTimeInMillis()) < aDay) {
//                    return false;
//                }
                if (sameDay(date, calendar)) {
                    return false;
                }
            }
        }
        return true;
    }

    private boolean sameDay(Date date, Calendar c2) {
        java.util.Calendar c1 = UDate.dateToCalendar(date);
        return c1.get(java.util.Calendar.YEAR) == c2.getYear() &&
                (c1.get(java.util.Calendar.MONTH) + 1) == c2.getMonth() &&
                c1.get(java.util.Calendar.DAY_OF_MONTH) == c2.getDay();
    }


    @Override
    public void onCalendarInterceptClick(Calendar calendar, boolean isClick) {
        showNotice("当前日期无病历");
    }

    @Override
    public void onMonthChange(int year, int month) {
        if (calendarRoot.isShown()) {
            this.year = year;
            this.month = month;
            this.day = calendarView.getCurDay();
            //月份改变事件
            tMonthPick.setText(year + "年" + month + "月");
        }
    }

    @Override
    public void onYearChange(int year) {
        if (calendarRoot.isShown()) {
            this.year = year;
            this.month = calendarView.getCurMonth();
            this.day = calendarView.getCurDay();
            //年份改变事件
            tMonthPick.setText(year + "年" + month + "月");
        }
    }

    @Override
    public void onBackPressed() {
        if (pImages != null && pImages.isShow()) {
            pImages.hide();
        } else {
            super.onBackPressed();
        }
    }
}
